﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using View.Core.Extensions;
using ViewFaceCore.Sharp;
using FaceDetectionDemo.Common;
using FaceDetectionDemo.Models;

namespace FaceDetectionDemo.BLL
{
    public class Deal
    {
        public static readonly Deal Instance = new Deal();
        private Deal()
        {
            try
            {

            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "Deal Err:" + ex.Message);
            }
        }


        /// <summary>
        /// 人脸位置信息集合
        /// </summary>
        List<Rectangle> FaceRectangles = new List<Rectangle>();
        /// <summary>
        /// 人脸 Pid 集合
        /// </summary>
        List<int> Pids = new List<int>();
        /// <summary>
        /// 人脸对应的年龄集合
        /// </summary>
        List<int> Ages = new List<int>();
        /// <summary>
        /// 性别集合
        /// </summary>
        List<string> Gender = new List<string>();

        /// <summary>
        /// 人脸识别库
        /// </summary>
        ViewFace viewFace = new ViewFace(((str) =>
        {
            try
            {
                LogWrite.TxtExport_DateNow("LogTrace.txt", "【初始化人脸识别类对像】:" + str);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "Deal ViewFace Create Err:" + ex.Message);
            }
        }));


        /// <summary>
        /// 人脸图片对像(同 人脸图片路径文件  二选一)
        /// </summary>
        public Image FaceImg { get; set; }

        private string faceImgPathFile = "";
        /// <summary>
        /// 人脸图片路径文件(同 人脸图片对像  二选一)
        /// </summary>
        public string FaceImgPathFile
        {
            get
            {
                return faceImgPathFile;
            }
            set
            {
                try
                {
                    faceImgPathFile = value;
                    this.FaceImg = null;
                    this.FaceImg = Image.FromFile(faceImgPathFile);
                }
                catch (Exception ex)
                {
                    LogWrite.TxtExport_DateNow("LogErr.txt", "Deal FaceImgPathFile Err:" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 人脸检测
        /// </summary>
        /// <returns></returns>
        public /*async*/ /*Task<*/ResultModel/*>*/ FaceDetect()
        {
            ResultModel rm = new ResultModel()
            {
                Success = false,
                Msg = "",
                ResultSingleModelList = new List<ResultSingleModel>()
            };
            try
            {
                FaceRectangles.Clear(); Ages.Clear(); Pids.Clear(); Gender.Clear();
                //FaceRectangles.Clear();
                if (this.FaceImg == null)
                {
                    rm.Msg = "要识别的图像 不存在!";
                    return rm;
                }
                Bitmap bitmap = new Bitmap(this.FaceImg);
                Bitmap bitmap2 = new Bitmap(this.FaceImg);
                rm.OriginalImg = bitmap2;
                var infos = viewFace.FaceDetector(bitmap); // 识别画面中的人脸
                infos = viewFace.FaceDetectorAsync(bitmap).GetAwaiter().GetResult();
                int i0 = 0;
                foreach (var info in infos)
                {
                    var points = viewFace.FaceMark(bitmap, info);
                    ResultSingleModel rsm = new ResultSingleModel()
                    {
                        FaceScore = info.Score,
                        FaceRectangle = info.Location,
                        Pid = i0,
                        Age = viewFace.FaceAgePredictor(bitmap, points),//(await viewFace.FaceAgePredictorAsync(bitmap, await viewFace.FaceMarkAsync(bitmap, new ViewFaceCore.Sharp.Model.FaceInfo() { Location = info.Location, Score = info.Score }))),
                        Gender = viewFace.FaceGenderPredictor(bitmap, points).ToDescription()//((await viewFace.FaceGenderPredictorAsync(bitmap, await viewFace.FaceMarkAsync(bitmap, new ViewFaceCore.Sharp.Model.FaceInfo() { Location = info.Location, Score = info.Score }))).ToDescription())
                    };
                    FaceRectangles.Add(rsm.FaceRectangle);
                    Pids.Add(rsm.Pid);
                    Ages.Add(rsm.Age);
                    Gender.Add(rsm.Gender);
                    rm.ResultSingleModelList.Add(rsm);
                    i0++;
                }
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    if (FaceRectangles.Any())
                    {
                        g.DrawRectangles(new Pen(Color.Red, 4), FaceRectangles.ToArray());
                        string pid = "";
                        for (int i = 0; i < FaceRectangles.Count; i++)
                        {
                            if (Pids.Any())
                            { pid = $"| Pid: {Pids[i]}"; }
                            g.DrawString($"{Ages[i]} 岁 | {Gender[i]} {pid}", new Font("微软雅黑", 24), Brushes.Green, new PointF(FaceRectangles[i].X + FaceRectangles[i].Width + 24, FaceRectangles[i].Y));
                        }
                    }
                    Bitmap bmp = new Bitmap(bitmap.Width, bitmap.Height);
                    g.DrawImage(bmp, bitmap.Width, bitmap.Height);
                    rm.FinishImg = bmp;
                }
            }
            catch (Exception ex)
            {
                rm.Success = false;
                rm.Msg += ("Deal FaceDetect Err:" + ex.Message);
                LogWrite.TxtExport_DateNow("LogErr.txt", rm.Msg);
            }
            return rm;
        }
    }
}
